﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace WeixinSB.Tools
{
    public static class BufferExtension
    {
        public static byte[] BufferToBytes(IBuffer buf)
        {

            using (var dataReader = DataReader.FromBuffer(buf))
            {
                var bytes = new byte[buf.Capacity];
                dataReader.ReadBytes(bytes);

                return bytes;
            }
        }

        //IRandomAccessStream->Stream
        public static Stream IRandomAccessStreamToStream(IRandomAccessStream fileStream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(fileStream.GetInputStreamAt(0));

            return stream;
        }

        //IRandomAccessStream->Bytes[]
        public static async Task<Byte[]> IRandomAccessStreamToBytes(IRandomAccessStream fileStream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(fileStream.GetInputStreamAt(0));

            return await StreamToBytes(stream);
        }

        public static async Task<Byte[]> StreamToBytes(Stream stream)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                await stream.CopyToAsync(ms);
                return ms.ToArray();
            }
        }

        public static IBuffer BytesToBuffer(byte[] bytes)
        {

            using (var dataWriter = new DataWriter())
            {
                dataWriter.WriteBytes(bytes);

                return dataWriter.DetachBuffer();
            }
        }

        //public static Stream AsStream(this IBuffer buf)
        //{
        //    var bytes = BufferToBytes(buf);
        //    using (MemoryStream ms = new MemoryStream(bytes))
        //    {
        //        return ms;
        //    }
        //}
    }

}
